package com.cloudkinto.controller.order;


import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.service.order.OrderBigcommerceService;
import com.cloudkinto.service.order.OrderShopifyService;
import com.cloudkinto.service.order.vo.Export2ShipOrderReq;
import com.cloudkinto.service.order.vo.amazon.OrderAmazonExcelReq;
import com.cloudkinto.service.order.vo.amazon.UpdateSysMemoReq;
import com.cloudkinto.service.order.vo.shopify.OrderShopifyRes;
import com.cloudkinto.service.orderoutput.vo.OrderOutputAddReq;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.cloudkinto.base.BaseController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ding
 * @since 2022-11-08
 */
@RestController
@RequestMapping("/api/admin/bigcommerce")
public class OrderBigcommerceController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(OrderShopifyController.class);

    @Autowired
    private OrderBigcommerceService service;

    @GetMapping("/addInit")
    @ApiOperation(value = "新增初始化", notes = "新增初始化")
    public SingleResult addInit() {
        return service.addInit();
    }


    @UserSessionRequired
    @GetMapping("/sync")
    @ApiOperation(value = "同步订单", notes = "新增初始化")
    public SingleResult sync(Long shopId, String startDate, String endDate) {
        return service.sync(shopId, startDate, endDate);
    }

    @UserSessionRequired
    @GetMapping("/webhook/{type}")
    @ApiOperation(value = "同步订单", notes = "新增初始化")
    public SingleResult webhook(@PathParam("type")String type) {
        return service.webhook(type);
    }


    @UserSessionRequired
    @PostMapping("")
    @ApiOperation(value = "新增", notes = "新增")
    public SingleResult add(@RequestBody @Validated Object req) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return SingleResult.success("新增成功", service.add(req, userId));
    }

    @UserSessionRequired
    @GetMapping("/updateInit/{id}")
    @ApiOperation(value = "编辑初始化", notes = "编辑初始化")
    public SingleResult updateInit(@PathVariable("id") Long id) {
        return service.updateInit(id);
    }

    @UserSessionRequired
    @PutMapping("")
    @ApiOperation(value = "修改", notes = "修改")
    public SingleResult update(@RequestBody @Validated Object req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功", service.update(req, userId));
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    public SingleResult delete(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功", service.delete(id, userId));
    }

    @UserSessionRequired
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查看详情", notes = "根据id查看详情")
    @ApiResponses({@ApiResponse(code = 200, message = "", response = OrderShopifyRes.class)})
    public SingleResult detail(@PathVariable("id") Long id) {
        return SingleResult.success("查询成功", service.detail(id));
    }

    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return service.pageInit(userId, companyId);
    }

    @UserSessionRequired
    @GetMapping("/list")
    @ApiOperation(value = "查询", notes = "查询")
    public SingleResult list(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        map.put("keyword", keyword);
        return SingleResult.success("查询成功", service.getList(map));
    }

    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = OrderShopifyRes.class))
    public PageResult listPage(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        String isSendOut = request.getParameter("isSendOut");
        String sendState = request.getParameter("sendState");
        String payState = request.getParameter("payState");
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String shopId = request.getParameter("shopId");
        map.put("shopId", shopId);
        if (companyId != null)
            map.put("companyId", companyId + "");
        map.put("keyword", keyword);
        map.put("isSendOut", isSendOut);
        map.put("sendState", sendState);
        map.put("payState", payState);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("current", current);
        map.put("pageSize", size);
        return service.getListPage(map);
    }

    @UserSessionRequired
    @PostMapping("exportExcel")
    @ApiOperation(value = "导出所有数据excel")
    public void exportAll(@RequestBody OrderAmazonExcelReq req, HttpServletResponse response) throws Exception {
        Long companyId = getCompanyId();
        Map<String, String> map = new HashMap<>();
        String keyword = req.getKeyword();
        String startTime = req.getStartTime();
        String endTime = req.getEndTime();
        String orderStatus = req.getOrderStatus();
        String fulfillmentChannel = req.getFulfillmentChannel();
        String isSendOut = req.getIsSendOut();

        map.put("companyId", String.valueOf(companyId));
        map.put("keyword", keyword);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("orderStatus", orderStatus);
        map.put("fulfillmentChannel", fulfillmentChannel);
        map.put("isSendOut", isSendOut);
        service.exportExcel(map, req, response);
    }

    @UserSessionRequired
    @PostMapping("mark/sendOut")
    @ApiOperation(value = "标记为发货", notes = "标记为发货")
    public SingleResult markSendOut(@RequestBody List<Long> ids) throws Exception {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return service.markSendOut(ids, userId);
    }

    @UserSessionRequired
    @PutMapping("systemMemo")
    @ApiOperation(value = "编辑系统备注", notes = "")
    public SingleResult systemMemo(@RequestBody @Validated UpdateSysMemoReq req) throws Exception {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return service.updateSysMemo(req, userId, companyId);
    }

    @UserSessionRequired
    @GetMapping("systemMemoInit")
    @ApiOperation(value = "编辑系统备注初始化", notes = "")
    public SingleResult systemMemoInit(@RequestParam Long id) throws Exception {
        return service.systemMemoInit(id);
    }

    @UserSessionRequired
    @PostMapping("sendOut")
    @ApiOperation(value = "发货", notes = "发货")
    public SingleResult sendOut(@RequestBody Export2ShipOrderReq req) throws Exception {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        if (req.getIsSolo() == 0) {
            return service.sendOut(req.getOrderids(), userId, companyId, false);
        } else {
            return service.sendOutNopackage(req.getOrderids()[0], userId, companyId);
        }
    }

    @UserSessionRequired
    @PostMapping("sendOutMatch")
    @ApiOperation(value = "确认发货发货", notes = "确认发货发货")
    public SingleResult sendOutMatch(@RequestBody List<OrderOutputAddReq> orderOutputAddReqList) throws Exception {
        Long userId = getCurrentUserId();
        return service.sendOutMatch(orderOutputAddReqList, userId, false);
    }

}

